package Controller;

import java.util.ArrayList;
import java.util.Iterator;

import Model.AdministradorCosechas;
import Model.Mineral;
import Model.ObjectViews.MineralView;
import View.ABMMineralView;

public class ABMMineralController 
{
	private String action;
	private ABMMineralView view;
	private ArrayList<MineralView> mineralesActivosView;
	private ArrayList<Mineral> mineralesActivos;
	private Mineral mineralActual;
	
	public ABMMineralController(String action, ABMMineralView view)
	{
		this.action = action;
		this.view = view;
	}
	
	public void init()
	{
		this.cargarMineralesActivos();
		
		view.showPanelDeEdicion(action == "ALTA");
		view.showGrillaDeMinerales(true);
		
		view.showBotonCancelar(true);
		view.showBotonGuardar(action == "MODIFICACION" || action == "ALTA");
		view.showBotonEliminar(action == "BAJA");
	}
	
	public void seleccionarMineral(int index)
	{
		if(action == "ALTA")
		{
			return;
		}
		
		mineralActual = mineralesActivos.get(index);
		view.setItemData(mineralActual.getView());
		view.showPanelDeEdicion(true);
	}
	
	public void Guardar()
	{
		MineralView mineralView = view.getItemData();
		
		if (action == "ALTA")
		{
			AdministradorCosechas.getSharedInstance().addMineral(mineralView.getCodigo(), mineralView.getNombre());
			view.setItemData(new MineralView());
		}
		else
		{
			mineralActual.setCodigo(mineralView.getCodigo());
			mineralActual.setNombre(mineralView.getNombre());
			view.showPanelDeEdicion(false);
		}
		
		this.cargarMineralesActivos();
	}
	
	public void Eliminar()
	{
		mineralActual.setActivo(false);
		mineralActual = null;
		view.showPanelDeEdicion(false);
		this.cargarMineralesActivos();
	}
	
	public void Cancelar()
	{
		if (action == "ALTA")
		{
			view.setItemData(new MineralView());
		}
		else
		{
			view.showPanelDeEdicion(false);
		}
	}
	
	//Metodos privados
	private void cargarMineralesActivos()
	{
		mineralesActivosView = new ArrayList<MineralView>();
		mineralesActivos = AdministradorCosechas.getSharedInstance().getMineralesActivos();
		
		for (Iterator<Mineral> iterator = mineralesActivos.iterator(); iterator.hasNext();) 
		{
			Mineral mineral = (Mineral) iterator.next();
			mineralesActivosView.add(mineral.getView());
		}
		
		view.setMineralesGrid(mineralesActivosView);
	}
}
